/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useMemo, useEffect } from 'react';
import { connect } from 'dva';
import moment from 'moment/moment';
import StatisticalData from './StatisticalData';

const formItemLayout = {
  labelCol: {
    xs: { span: 0 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

const startDate = moment()
  .startOf('day')
  .subtract(1, 'days');
const endDate = moment()
  .endOf('day')
  .subtract(1, 'days');

const listTypeMapToRankType = {
  inNumDetailList: 'inNumRank',
  outRateDetailList: 'outRateRank',
  sendOrderDetailList: 'orderNumRank',
  fansDetailList: 'fansNumRank',
};

const listTypeMapToRankReqType = {
  inNumDetailList: 'in',
  outRateDetailList: 'out_rate',
  sendOrderDetailList: 'order',
  fansDetailList: 'fans',
};

const listTypeMapToChartTitle = {
  inNumDetailList: '入库排名前20',
  outRateDetailList: '出库率排名前20',
  sendOrderDetailList: '订单排名前20',
  fansDetailList: '新增粉丝数排名前20',
};

const effectsMapToListType = {
  inNumDetailList: {
    // 入库数
    table: 'inNumDetailList',
    chart: 'regionalRanking',
  },
  outRateDetailList: {
    // 出库率
    table: 'outRateDetailList',
    chart: 'regionalRanking',
  },
  sendOrderDetailList: {
    // 寄件订单
    table: 'sendOrderDetailList',
    chart: 'regionalRanking',
  },
  fansDetailList: {
    // 公众号粉丝
    table: 'fansDetailList',
    chart: 'regionalRanking',
  },
};

const AreaRanking = props => {
  const {
    dispatch,
    userInfo,
    list,
    inNumLoading,
    activeKey,
    outRateLoading,
    sendOrderLoading,
    fansLoading,
    areaRankKey,
  } = props;
  const { branch = [], branchLevel, user_type } = userInfo;
  const {
    brandList,
    // listType: listTypeFromRedux, // 用于类型选择的判断
    listType = 'inNumDetailList', // 用于类型选择的判断
    areaInNumRank = [],
    areaOutRateRank = [],
    orderNumRank = [],
    fansNumRank = [],
    searchFormValues = {},
    inNumDetailList = {},
    outRateDetailList = {},
    sendOrderDetailList = {},
    fansDetailList = {},
  } = list;

  // 入库数据
  const { summary: inout_summary = {} } = inNumDetailList;
  const { storage_total, out_total, back_total } = inout_summary;
  // 寄件订单数
  const { summary: order_summary = {} } = sendOrderDetailList;
  const { total_order_num, total_real_order_num, total_fee_num } = order_summary || {};
  // 粉丝数据
  const { summary: fans_summary = {} } = fansDetailList;
  const { total_new_fans, total_fans } = fans_summary;

  // const [listType, setListType] = useState("inNumDetailList");
  const isZyAccount = user_type == '2';

  // 柱状图数据
  const chartList = useMemo(
    () => {
      switch (listType) {
        case 'inNumDetailList':
          return areaInNumRank;
        case 'outRateDetailList':
          return areaOutRateRank;
        case 'sendOrderDetailList':
          return orderNumRank;
        case 'fansDetailList':
          return fansNumRank;
        default:
          return [];
      }
    },
    [listType, orderNumRank, fansNumRank, areaInNumRank, areaOutRateRank],
  );

  const tableList = useMemo(
    () => {
      switch (listType) {
        case 'inNumDetailList':
          return inNumDetailList;
        case 'areaRanking':
          return inNumDetailList;
        case 'outRateDetailList':
          return outRateDetailList;
        case 'sendOrderDetailList':
          return sendOrderDetailList;
        case 'fansDetailList':
          return fansDetailList;
        default:
          return {
            list: [],
            pagination: null,
          };
      }
    },
    [outRateDetailList, sendOrderDetailList, inNumDetailList, fansDetailList, listType],
  );

  const columns = useMemo(
    () => ({
      inNumDetailList: [
        {
          title: '日期',
          dataIndex: 'date',
        },
        {
          title: '驿站（区域）名称',
          dataIndex: 'abbr_name',
        },
        {
          title: '品牌',
          dataIndex: 'brand',
        },
        {
          title: `入库数 ${storage_total || 0} 条`,
          dataIndex: 'storage_num',
        },
        {
          title: `出库数 ${out_total || 0} 条`,
          dataIndex: 'out_num',
        },
        {
          title: `退回数 ${back_total || 0} 条`,
          dataIndex: 'back_num',
        },
      ],
      outRateDetailList: [
        {
          title: '日期',
          dataIndex: 'date',
        },
        {
          title: '驿站（区域）名称',
          dataIndex: 'abbr_name',
        },
        {
          title: '三日出库率%',
          dataIndex: 'out_rate',
          render: text => `${Math.floor(Number(text) * 100) / 100}%`,
        },
      ],
      sendOrderDetailList: [
        {
          title: '所选日期段',
          dataIndex: 'date',
        },
        {
          title: '驿站（区域）名称',
          dataIndex: 'abbr_name',
        },
        {
          title: '品牌',
          dataIndex: 'brand',
        },
        {
          title: `订单数 ${total_order_num || 0} 条`,
          dataIndex: 'order_num',
        },
        {
          title: `实名订单 ${total_real_order_num || 0} 条`,
          dataIndex: 'real_order_num',
        },
        {
          title: `快递费 ${total_fee_num || 0} 元`,
          dataIndex: 'fee_num',
        },
      ],
      fansDetailList: [
        {
          title: '日期',
          dataIndex: 'date',
        },
        {
          title: '驿站名称',
          dataIndex: 'abbr_name',
        },
        {
          title: `新增粉丝 ${total_new_fans || 0} 条`,
          dataIndex: 'new_fans',
        },
        {
          title: `累计粉丝 ${total_fans || 0} 条`,
          dataIndex: 'grand_fans',
        },
      ],
    }),
    [
      storage_total,
      out_total,
      back_total,
      total_order_num,
      total_real_order_num,
      total_new_fans,
      total_fans,
      total_fee_num,
    ],
  );

  const searchData = useMemo(
    () => {
      const {
        areaRankingAddressId = [],
        areaRankingBrandId,
        areaRankingDate = [startDate, endDate],
        listType: formListType,
        page,
      } = searchFormValues;
      const [start = '', end = ''] = areaRankingDate.map(d => moment(d).format('YYYY-MM-DD'));

      const values = {
        start_date: start,
        end_date: end,
        brand: areaRankingBrandId,
        code: [...areaRankingAddressId].pop(),
        page,
        pageSize: 20,
        formListType,
      };
      return values;
    },
    [searchFormValues],
  );

  useEffect(
    () => {
      let ini_branchId;
      let init_branch;
      if (branchLevel == 0 && branch.length == 0 && isZyAccount) {
        init_branch = [
          {
            id: '0',
            name: '中国邮政集团有限公司',
            level: '0',
            pid: '-2', // 自定义pid用来区分是否是单独属于总公司账号
          },
        ];
        ini_branchId = ['0', '334'];
      } else {
        ini_branchId = branch.filter(val => (isZyAccount ? val.level != 0 : val)).map(i => i.id);
        init_branch = branch;
      }
      // 同步设置表单的初始数据后再去异步请求页面数据
      dispatch({
        type: 'list/setFormValues',
        payload: {
          areaRankingDate: [startDate, endDate],
          areaRankingSiteId: 'all',
          areaRankingAddressId: ini_branchId,
          areaRankingBrandId: 'all',
          areaRankingListType: 'areaRanking',
          listType: 'areaRanking',
          init_branch,
        },
      });
    },
    [isZyAccount, branch, branchLevel, dispatch],
  );

  useEffect(
    () => {
      // 通过监听搜索框的数据来请求当前页面的数据
      if (searchData.brand && searchData.formListType === 'areaRanking') {
        const { start_date, end_date, brand, code, page, pageSize, formListType } = searchData;
        const deletBrand =
          listTypeMapToRankReqType[listType] === 'out_rate' ||
          listTypeMapToRankReqType[listType] === 'fans';
        dispatch({
          type: `list/${effectsMapToListType[listType].chart}`,
          payload: {
            start_date,
            end_date,
            cm_id: 'all',
            brand: deletBrand ? undefined : brand,
            code,
            type: listTypeMapToRankReqType[listType],
            formListType,
            pageSize,
          },
        });
        dispatch({
          type: `list/${effectsMapToListType[listType].table}`,
          payload: {
            start_date,
            end_date,
            brand: deletBrand ? undefined : brand,
            code,
            page,
            pageSize,
            type: listTypeMapToRankReqType[listType],
          },
        });
      }
    },
    [searchData, dispatch, listType],
  );

  return (
    <div>
      <StatisticalData
        activeKey={activeKey}
        formItemLayout={formItemLayout}
        chartTitle={listTypeMapToChartTitle[listType]}
        dropList={brandList}
        loading={inNumLoading || outRateLoading || sendOrderLoading || fansLoading}
        data={tableList}
        histogramList={chartList}
        columns={columns[listType]}
        listType={listType}
        areaRankingListType="areaRanking"
        rankType={listTypeMapToRankType[listType]}
        // chart={effectsMapToListType[listType].chart}
        down="storage"
        areaRankKey={areaRankKey}
        statisticalType={
          listType === 'fansDetailList' || listType === 'outRateDetailList' ? 'brand' : ''
        }
      />
    </div>
  );
};

export default connect(({ loading, list, user }) => ({
  list,
  userInfo: user.currentUser.user_info,
  inNumLoading: loading.effects['list/inNumDetailList'],
  outRateLoading: loading.effects['list/outRateDetailList'],
  sendOrderLoading: loading.effects['list/sendOrderDetailList'],
  fansLoading: loading.effects['list/fansDetailList'],
}))(React.memo(AreaRanking));
